package model

import (
	"fmt"
	"gowork/cashier/utils"
	"strconv"
	"strings"
	"sync"
	"time"
)

type Store struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Address string
	AddProducts int
	AddItem int
	AddTreatmentPackage int
	OpenIntegral int
	PerIntegral int
	Exchange int
	PerformanceRule int
	Region int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type CustomerType struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	ConsumptionModeList []*ConsumptionMode `xorm:"-"`
	ModifiableItemList []*ModifiableItem `xorm:"-"`
	PaymentMethodLsit []*PaymentMethods `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type CustomerTypePaymentMethod struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerTypeId int64
	PaymentMethodId int64
	StoreId int64
	IsAny bool `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type CustomerTypeConsumptionMode struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerTypeId int64
	ConsumptionModeId int64
	StoreId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type CashierRule struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerTypeId int64
	ModifiableItemId int64
	StoreId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ModifiableItem struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Modifi bool `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Consumption struct {
	Id int64 `xorm:"pk autoincr"`
	Type int64
	MemberType int64
	MemberId int64
	StoreId int64
	ConsumptionProductList []*ConsumptionProducts `xorm:"-"`
	ConsumptionItemList []*ConsumptionItems `xorm:"-"`
	ConsumptionTreatmentList []*ConsumptionTreatment `xorm:"-"`
	Amount float64
	PaymentDetails []*ConsumptionPaymentMethods `xorm:"-"`
	ActualPerformance int64
	SerialNo int64
	Remarks string
	GiftItemList []*GiftItems `xorm:"-"`
	ThisSumPoint int64
	State int
	Source int
	ConsumptionMemberPurchasePackageList []*ConsumptionMemberPurchasePackage `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type GiftItems struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	ItemId int64
	Number int64
	Name string
	Compose bool
	OriginalPrice float64
	NumberOfGifts int
	TotalValue float64
	EffectiveDays int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionModePoint struct {
	Id int64 `xorm:"pk autoincr"`
	StoreId int64
	ConsumptionModeId int64
	AmountOfPoints int64
	Integral int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionMode struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Exist bool `xorm:"-"`
	PaymentMethodList []*PaymentMethods `xorm:"-"`
	ConsumptionModePoint ConsumptionModePoint `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type IntegralRule struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionModeId int64
	PaymentMethodId int64
	StoreId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type PaymentMethods struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Ident bool `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionPaymentMethods struct {
	Id int64 `xorm:"pk autoincr"`
	PaymentTypeId int64
	ConsumptionId int64
	Name string
	PaymentAmount float64
	ThisPoint int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Products struct {
	Id int64 `xorm:"pk autoincr"`
	StoreId int64
	Number int64
	Name string
	OriginalPrice float64
	Price float64
	Stock int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionProducts struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	ProductId int64
	Number int64
	Name string
	OriginalPrice float64
	Discount int
	Price float64
	Achievement int64
	ConsumptionEmployeeList []*ConsumptionEmployees `xorm:"-"`
	ConsumptionBeauticianList []*ConsumptionBeautician `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionItems struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	ItemId int64
	Number int64
	Name string
	Compose bool
	OriginalPrice float64
	Discount int
	Price float64
	EffectiveDays int
	Achievement int64
	ConsumptionEmployeeList []*ConsumptionEmployees `xorm:"-"`
	ConsumptionBeauticianList []*ConsumptionBeautician `xorm:"-"`
	ConsumptionDate string
	Frequency int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type TreatmentProducts struct {
	Id int64 `xorm:"pk autoincr"`
	TreatmentId int64
	ProductId int64
	Number int64
	Name string
	OriginalPrice float64
	Discount int
	Price float64
	Quantity int64
	Achievement int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Items struct {
	Id int64 `xorm:"pk autoincr"`
	StoreId int64
	ComposeItemId int64
	Compose bool
	ItemList []*Items `xorm:"-"`
	Number int64
	Name string
	OriginalPrice float64
	EffectiveDays int
	StoreSale int64 `xorm:"-"`
	StorePackage int64 `xorm:"-"`
	CashPerformance int64 `xorm:"-"`
	ConsumptionPerformance int64 `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type TreatmentItems struct {
	Id int64 `xorm:"pk autoincr"`
	TreatmentId int64
	ItemId int64
	ComposeTtemId int64
	Compose bool
	Number int64
	Name string
	OriginalPrice float64
	Discount int
	Price float64
	EffectiveDays int
	Achievement int64
	Frequency int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionTreatment struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	TreatmentId int64
	Number int64
	Name string
	OriginalPrice float64
	Details string
	Discount int
	Price float64
	Achievement int64
	ConsumptionEmployeeList []*ConsumptionEmployees `xorm:"-"`
	ConsumptionBeauticianList []*ConsumptionBeautician `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionEmployees struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	ConsumptionProductOrItemId int64
	ClerkId int64
	Name string
	Achievement int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionBeautician struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionProductOrItemId int64
	ConsumptionId int64
	ClerkId int64
	Name string
	Achievement int64
	ManualCost int32
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Clerk struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	RoleId int64
	RoleName string
	AchievementSum int64
	ManualCostSum int32
	CreatedAt time.Time
	UpdatedAt time.Time
}

type MeiyeMember struct { //会员
	Id int64 `xorm:"pk autoincr"`
	Name string
	MemberInformationList []*MemberInformation `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type MemberInformation struct { //会员卡
	Id int64 `xorm:"pk autoincr"`
	StoreId int64
	Name string
	Type int
	AccountAmount float64
	MemberPurchasePackageList []*MemberPurchasePackage `xorm:"-"`
	MemberPoints int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type MemberPurchasePackage struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	ItemId int64
	Compose bool
	MemberInformationId int64
	Number int64
	Name string
	TimesOfOriginalTreatment int
	UsageTimes int
	RemainingTimes int
	EffectiveDays int
	OriginalPrice float64
	CoursePrice float64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ConsumptionMemberPurchasePackage struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	MemberPurchasePackageId int64
	ItemId int64
	Compose bool
	Number int64
	Name string
	ClerkId int64
	Achievement int64
	ManualCost int32
	TimesOfOriginalTreatment int
	RemainingTimes int
	ConsumptionEmployeeList []*ConsumptionEmployees `xorm:"-"`
	ConsumptionBeauticianList []*ConsumptionBeautician `xorm:"-"`
	EffectiveDays int
	OriginalPrice float64
	CoursePrice float64
	ComposeItemList []*ComposeItem `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ComposeItem struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionMemberPurchasePackageId int64
	Name string
	Number int64
	ConsumptionEmployeeList []*ConsumptionEmployees `xorm:"-"`
	ConsumptionBeauticianList []*ConsumptionBeautician `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type SmallTicketType struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionModeId int64
	Name string
	PrintInfoTypeList []*PrintInfoType `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type PrintInfoType struct {
	Id int64 `xorm:"pk autoincr"`
	SmallTicketTypeId int64
	Name string
	SmallTicketFieldList []*SmallTicketField `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type SmallTicketField struct {
	Id int64 `xorm:"pk autoincr"`
	PrintInfoTypeId int64
	StoreId int
	Name string
	Print bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

func QuerySmallTicket(sttId int64, sId int)(*SmallTicketType, error){
	var stt SmallTicketType
	x.Id(sttId).Get(&stt)

	x.Where("small_ticket_type_id = ?", sttId).Find(&stt.PrintInfoTypeList)
	for _, pit := range stt.PrintInfoTypeList{
		x.Where("print_info_type_id = ?", pit.Id).And("store_id = ?", sId).Find(&pit.SmallTicketFieldList)
	}

	return &stt, nil
}

func PrintTicket(sId int, cmId int64)(*SmallTicketType, error){

	var stt SmallTicketType
	x.Where("consumption_mode_id = ?", cmId).Get(&stt)

	x.Where("small_ticket_type_id = ?", stt.Id).Find(&stt.PrintInfoTypeList)
	for _, pit := range stt.PrintInfoTypeList{
		x.Where("print_info_type_id = ?", pit.Id).And("store_id = ?", sId).And("print = ?", true).Find(&pit.SmallTicketFieldList)
	}

	return &stt, nil

}

func InsertSmallTicket(stt *SmallTicketType, sId int)(map[string]interface{}, error){

	x.Where("store_id = ?", sId).Delete(new(SmallTicketField))

	for _, pit := range stt.PrintInfoTypeList{
		for _, stf := range pit.SmallTicketFieldList{

			stf.StoreId = sId
			x.Insert(pit)
		}
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (consumption *Consumption)InsertComposeTtem(i *Items)(map[string]interface{}, error){
	if i.Compose{
		x.Insert(i)
		for _, iv := range i.ItemList{
			iv.ComposeItemId = i.Id
			x.Id(iv.Id).Update(iv)
		}
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (consumption *Consumption)QueryComposeTtem()([]*Items, error){
	var iList []*Items
	x.Find(&iList)
	for _, iv := range iList{
		if iv.Compose{
			x.Where("compose_item_id = ?", iv.Id).Find(&iv.ItemList)
		}
	}
	return iList, nil
}

func (consumption *Consumption)CourseConsumption(c *Consumption)(map[string]interface{}, error){

	w := new(utils.Worker)

	var s Store
	x.Id(c.StoreId).Get(&s)

	c.Id = w.GetId()
	c.CreatedAt = time.Now()
	c.UpdatedAt = time.Now()
	x.Insert(c)

	for _, pv := range c.PaymentDetails {

		//积分兑换
		//if pv.Id == 10{
		//	mf := new(MemberInformation)
		//	x.Id(cv.MemberId).Get(mf)
		//	mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
		//	x.Id(mf.Id).Update(mf)
		//}

		pv.ConsumptionId = c.Id
		pv.CreatedAt = time.Now()
		pv.UpdatedAt = time.Now()
		x.Insert(pv)

		var ir IntegralRule
		x.Where("payment_method_id = ?", pv.PaymentTypeId).
			And("store_id = ?", c.StoreId).
			And("consumption_mode_id = ?", c.Type).Get(&ir)
		if s.OpenIntegral == 1 && ir.Id != 0{
			var cmp ConsumptionModePoint
			x.Where("store_id = ?", c.StoreId).And("consumption_mode_id = ?", c.Type).Get(&cmp)
			var thisPoint int64 = int64(pv.PaymentAmount)*int64(cmp.Integral/cmp.AmountOfPoints)

			mf := new(MemberInformation)
			mf.MemberPoints += thisPoint
			x.Id(c.MemberId).Update(mf)
			pv.ThisPoint = thisPoint
			x.Id(pv.Id).Update(pv)
			c.ThisSumPoint += thisPoint
			x.Id(c.Id).Update(c)
		}

		if pv.PaymentTypeId == 308720610148614152{
			mf := new(MemberInformation)
			mf.AccountAmount -= pv.PaymentAmount
			x.Id(c.MemberId).Update(mf)
		}

		if pv.PaymentTypeId == 308720610148614151{
			mf := new(MemberInformation)
			x.Id(c.MemberId).Get(mf)
			mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
			x.Id(mf.Id).Update(mf)
		}
	}

	for _, cmpp := range c.ConsumptionMemberPurchasePackageList{

		cmpp.Id = w.GetId()
		cmpp.ConsumptionId = c.Id
		cmpp.CreatedAt = time.Now()
		cmpp.UpdatedAt = time.Now()
		x.Insert(cmpp)

		for _, icev := range cmpp.ConsumptionEmployeeList {

			var ic Clerk
			x.Id(icev.ClerkId).Get(&ic)
			ic.AchievementSum += icev.Achievement
			x.Id(icev.ClerkId).Update(&ic)

			icev.Id = w.GetId()
			icev.ConsumptionProductOrItemId = cmpp.Id
			icev.ConsumptionId = c.Id
			icev.CreatedAt = time.Now()
			icev.UpdatedAt = time.Now()
			x.Insert(icev)
		}

		for _, icbv := range cmpp.ConsumptionBeauticianList {

			var ic Clerk
			x.Id(icbv.ClerkId).Get(&ic)
			ic.AchievementSum += icbv.Achievement
			ic.ManualCostSum += icbv.ManualCost
			x.Id(icbv.ClerkId).Update(&ic)

			icbv.Id = w.GetId()
			icbv.ConsumptionProductOrItemId = cmpp.Id
			icbv.ConsumptionId = c.Id
			icbv.CreatedAt = time.Now()
			icbv.UpdatedAt = time.Now()
			x.Insert(icbv)
		}

		if cmpp.Compose == true{
			for _, ct := range cmpp.ComposeItemList{

				ct.Id = w.GetId()
				ct.ConsumptionMemberPurchasePackageId = cmpp.Id
				ct.CreatedAt = time.Now()
				ct.UpdatedAt = time.Now()
				x.Insert(ct)

				for _, icev := range ct.ConsumptionEmployeeList {

					var ic Clerk
					x.Id(icev.ClerkId).Get(&ic)
					ic.AchievementSum += icev.Achievement
					x.Id(icev.ClerkId).Update(&ic)

					icev.Id = w.GetId()
					icev.ConsumptionProductOrItemId = ct.Id
					icev.ConsumptionId = c.Id
					icev.CreatedAt = time.Now()
					icev.UpdatedAt = time.Now()
					x.Insert(icev)
				}

				for _, icbv := range ct.ConsumptionBeauticianList {

					var ic Clerk
					x.Id(icbv.ClerkId).Get(&ic)
					ic.AchievementSum += icbv.Achievement
					ic.ManualCostSum += icbv.ManualCost
					x.Id(icbv.ClerkId).Update(&ic)

					icbv.Id = w.GetId()
					icbv.ConsumptionProductOrItemId = ct.Id
					icbv.ConsumptionId = c.Id
					icbv.CreatedAt = time.Now()
					icbv.UpdatedAt = time.Now()
					x.Insert(icbv)
				}
			}
		}

		var mpp MemberPurchasePackage
		x.Id(cmpp.MemberPurchasePackageId).Get(&mpp)
		mpp.UsageTimes += 1
		mpp.RemainingTimes -= 1
		x.Id(cmpp.MemberPurchasePackageId).Update(&mpp)
	}
	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (consumption *Consumption)CourseConsumptionAsync(c *Consumption)(map[string]interface{}, error){

	w := new(utils.Worker)

	var s Store
	x.Id(c.StoreId).Get(&s)

	c.Id = w.GetId()
	c.CreatedAt = time.Now()
	c.UpdatedAt = time.Now()
	x.Insert(c)

	var wg sync.WaitGroup
	wg.Add(7)

	for i := 0; i < 4; i++ {
		var actual int = i
		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			pv := c.PaymentDetails[actual]

			//积分兑换
			//if pv.Id == 10{
			//	mf := new(MemberInformation)
			//	x.Id(cv.MemberId).Get(mf)
			//	mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
			//	x.Id(mf.Id).Update(mf)
			//}

			pv.ConsumptionId = c.Id
			pv.CreatedAt = time.Now()
			pv.UpdatedAt = time.Now()
			x.Insert(pv)

			var ir IntegralRule
			x.Where("payment_method_id = ?", pv.PaymentTypeId).
				And("store_id = ?", c.StoreId).
				And("consumption_mode_id = ?", c.Type).Get(&ir)
			if s.OpenIntegral == 1 && ir.Id != 0 {
				var cmp ConsumptionModePoint
				x.Where("store_id = ?", c.StoreId).And("consumption_mode_id = ?", c.Type).Get(&cmp)
				var thisPoint int64 = int64(pv.PaymentAmount) * int64(cmp.Integral/cmp.AmountOfPoints)

				mf := new(MemberInformation)
				mf.MemberPoints += thisPoint
				x.Id(c.MemberId).Update(mf)
				pv.ThisPoint = thisPoint
				x.Id(pv.Id).Update(pv)
				c.ThisSumPoint += thisPoint
				x.Id(c.Id).Update(c)
			}

			if pv.PaymentTypeId == 308720610148614152 {
				mf := new(MemberInformation)
				mf.AccountAmount -= pv.PaymentAmount
				x.Id(c.MemberId).Update(mf)
			}

			if pv.PaymentTypeId == 308720610148614151 {
				mf := new(MemberInformation)
				x.Id(c.MemberId).Get(mf)
				mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
				x.Id(mf.Id).Update(mf)
			}

			wg.Done()
		}()
	}

	for i := 0; i < 3; i++ {
		var actual int = i
		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			cmpp := c.ConsumptionMemberPurchasePackageList[actual]

			cmpp.Id = w.GetId()
			cmpp.ConsumptionId = c.Id
			cmpp.CreatedAt = time.Now()
			cmpp.UpdatedAt = time.Now()
			x.Insert(cmpp)

			for _, icev := range cmpp.ConsumptionEmployeeList {

				var ic Clerk
				x.Id(icev.ClerkId).Get(&ic)
				ic.AchievementSum += icev.Achievement
				x.Id(icev.ClerkId).Update(&ic)

				icev.Id = w.GetId()
				icev.ConsumptionProductOrItemId = cmpp.Id
				icev.ConsumptionId = c.Id
				icev.CreatedAt = time.Now()
				icev.UpdatedAt = time.Now()
				x.Insert(icev)
			}

			for _, icbv := range cmpp.ConsumptionBeauticianList {

				var ic Clerk
				x.Id(icbv.ClerkId).Get(&ic)
				ic.AchievementSum += icbv.Achievement
				ic.ManualCostSum += icbv.ManualCost
				x.Id(icbv.ClerkId).Update(&ic)

				icbv.Id = w.GetId()
				icbv.ConsumptionProductOrItemId = cmpp.Id
				icbv.ConsumptionId = c.Id
				icbv.CreatedAt = time.Now()
				icbv.UpdatedAt = time.Now()
				x.Insert(icbv)
			}

			if cmpp.Compose == true {
				for _, ct := range cmpp.ComposeItemList {

					ct.Id = w.GetId()
					ct.ConsumptionMemberPurchasePackageId = cmpp.Id
					ct.CreatedAt = time.Now()
					ct.UpdatedAt = time.Now()
					x.Insert(ct)

					for _, icev := range ct.ConsumptionEmployeeList {

						var ic Clerk
						x.Id(icev.ClerkId).Get(&ic)
						ic.AchievementSum += icev.Achievement
						x.Id(icev.ClerkId).Update(&ic)

						icev.Id = w.GetId()
						icev.ConsumptionProductOrItemId = ct.Id
						icev.ConsumptionId = c.Id
						icev.CreatedAt = time.Now()
						icev.UpdatedAt = time.Now()
						x.Insert(icev)
					}

					for _, icbv := range ct.ConsumptionBeauticianList {

						var ic Clerk
						x.Id(icbv.ClerkId).Get(&ic)
						ic.AchievementSum += icbv.Achievement
						ic.ManualCostSum += icbv.ManualCost
						x.Id(icbv.ClerkId).Update(&ic)

						icbv.Id = w.GetId()
						icbv.ConsumptionProductOrItemId = ct.Id
						icbv.ConsumptionId = c.Id
						icbv.CreatedAt = time.Now()
						icbv.UpdatedAt = time.Now()
						x.Insert(icbv)
					}
				}
			}

			var mpp MemberPurchasePackage
			x.Id(cmpp.MemberPurchasePackageId).Get(&mpp)
			mpp.UsageTimes += 1
			mpp.RemainingTimes -= 1
			x.Id(cmpp.MemberPurchasePackageId).Update(&mpp)

			wg.Done()
		}()
	}

	wg.Wait()

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (c *Consumption) PlaceAnOrder(cv *Consumption) (map[string]interface{}, error){

	w := new(utils.Worker)
	var mpp MemberPurchasePackage

	if cv.Type == 308731091139690499 && cv.MemberType == 308720021171863552{

		cv.Id = w.GetId()
		cv.CreatedAt = time.Now()
		cv.UpdatedAt = time.Now()
		x.Insert(cv)
		for _, cpv := range cv.ConsumptionProductList {

			cpv.Id = w.GetId()
			cpv.ConsumptionId = cv.Id
			cpv.CreatedAt = time.Now()
			cpv.UpdatedAt = time.Now()
			x.Insert(cpv)

			var p Products
			x.Id(cpv.ProductId).Get(&p)
			p.Stock -= 1
			x.Id(cpv.ProductId).Update(&p)

			for _, pcev := range cpv.ConsumptionEmployeeList {

				var pc Clerk
				x.Id(pcev.ClerkId).Get(&pc)
				pc.AchievementSum += pcev.Achievement
				x.Id(pcev.ClerkId).Update(&pc)

				pcev.Id = w.GetId()
				pcev.ConsumptionProductOrItemId = cpv.Id
				pcev.ConsumptionId = cv.Id
				pcev.CreatedAt = time.Now()
				pcev.UpdatedAt = time.Now()
				x.Insert(pcev)
			}

			for _, pcbv := range cpv.ConsumptionBeauticianList {

				var pc Clerk
				x.Id(pcbv.ClerkId).Get(&pc)
				pc.AchievementSum += pcbv.Achievement
				pc.ManualCostSum += pcbv.ManualCost
				x.Id(pcbv.ClerkId).Update(&pc)

				pcbv.Id = w.GetId()
				pcbv.ConsumptionProductOrItemId = cpv.Id
				pcbv.ConsumptionId = cv.Id
				pcbv.CreatedAt = time.Now()
				pcbv.UpdatedAt = time.Now()
				x.Insert(pcbv)
			}
		}

		for _, civ := range cv.ConsumptionItemList {
			civ.Id = w.GetId()
			civ.ConsumptionId = cv.Id
			civ.CreatedAt = time.Now()
			civ.UpdatedAt = time.Now()
			x.Insert(civ)

			mpp.Id = w.GetId()
			mpp.ConsumptionId = cv.Id
			mpp.ItemId = civ.ItemId
			mpp.MemberInformationId = cv.MemberId
			mpp.Number = civ.Number
			mpp.Name = civ.Name
			mpp.Compose = civ.Compose
			mpp.TimesOfOriginalTreatment = civ.Frequency
			mpp.RemainingTimes = civ.Frequency
			mpp.OriginalPrice = civ.OriginalPrice
			mpp.CoursePrice = civ.Price
			mpp.EffectiveDays = civ.EffectiveDays
			mpp.CreatedAt = time.Now()
			mpp.UpdatedAt = time.Now()
			x.Insert(&mpp)

			for _, icev := range civ.ConsumptionEmployeeList {

				var ic Clerk
				x.Id(icev.ClerkId).Get(&ic)
				ic.AchievementSum += icev.Achievement
				x.Id(icev.ClerkId).Update(&ic)

				icev.Id = w.GetId()
				icev.ConsumptionProductOrItemId = civ.Id
				icev.ConsumptionId = cv.Id
				icev.CreatedAt = time.Now()
				icev.UpdatedAt = time.Now()
				x.Insert(icev)
			}

			for _, icbv := range civ.ConsumptionBeauticianList {

				var ic Clerk
				x.Id(icbv.ClerkId).Get(&ic)
				ic.AchievementSum += icbv.Achievement
				ic.ManualCostSum += icbv.ManualCost
				x.Id(icbv.ClerkId).Update(&ic)

				icbv.Id = w.GetId()
				icbv.ConsumptionProductOrItemId = civ.Id
				icbv.ConsumptionId = cv.Id
				icbv.CreatedAt = time.Now()
				icbv.UpdatedAt = time.Now()
				x.Insert(icbv)
			}
		}

		for _, ctv := range cv.ConsumptionTreatmentList{

			ctv.Id = w.GetId()
			ctv.ConsumptionId = cv.Id
			ctv.CreatedAt = time.Now()
			ctv.UpdatedAt = time.Now()
			x.Insert(ctv)

			var tpList []*TreatmentProducts
			x.Where("treatment_id = ?", ctv.TreatmentId).Find(&tpList)
			for _, tp := range tpList {
				var p Products
				x.Id(tp.ProductId).Get(&p)
				p.Stock -= tp.Quantity
				x.Id(tp.ProductId).Update(&p)
			}

			var tiList []*TreatmentItems
			x.Where("treatment_id = ?", ctv.TreatmentId).Find(&tiList)
			for _, iv := range tiList{
				mpp.Id = w.GetId()
				mpp.ConsumptionId = cv.Id
				mpp.ItemId = iv.ItemId
				mpp.MemberInformationId = cv.MemberId
				mpp.Number = iv.Number
				mpp.Name = iv.Name
				mpp.Compose = iv.Compose
				mpp.TimesOfOriginalTreatment = iv.Frequency
				mpp.RemainingTimes = iv.Frequency
				mpp.OriginalPrice = iv.OriginalPrice
				mpp.CoursePrice = iv.Price
				mpp.EffectiveDays = iv.EffectiveDays
				mpp.CreatedAt = time.Now()
				mpp.UpdatedAt = time.Now()
				x.Insert(&mpp)
			}

			for _, tcev := range ctv.ConsumptionEmployeeList {

				var tc Clerk
				x.Id(tcev.ClerkId).Get(&tc)
				tc.AchievementSum += tcev.Achievement
				x.Id(tcev.ClerkId).Update(&tc)

				tcev.Id = w.GetId()
				tcev.ConsumptionProductOrItemId = ctv.Id
				tcev.ConsumptionId = cv.Id
				tcev.CreatedAt = time.Now()
				tcev.UpdatedAt = time.Now()
				x.Insert(tcev)
			}

			for _, tcbv := range ctv.ConsumptionBeauticianList {

				var tc Clerk
				x.Id(tcbv.ClerkId).Get(&tc)
				tc.AchievementSum += tcbv.Achievement
				tc.ManualCostSum += tcbv.ManualCost
				x.Id(tcbv.ClerkId).Update(&tc)

				tcbv.Id = w.GetId()
				tcbv.ConsumptionProductOrItemId = ctv.Id
				tcbv.ConsumptionId = cv.Id
				tcbv.CreatedAt = time.Now()
				tcbv.UpdatedAt = time.Now()
				x.Insert(tcbv)
			}
		}

		var s Store
		x.Id(cv.StoreId).Get(&s)

		for _, pv := range cv.PaymentDetails {

			pv.Id = w.GetId()
			pv.ConsumptionId = cv.Id
			pv.CreatedAt = time.Now()
			pv.UpdatedAt = time.Now()
			x.Insert(pv)

			var ir IntegralRule
			x.Where("payment_method_id = ?", pv.PaymentTypeId).
				And("store_id = ?", cv.StoreId).
				And("consumption_mode_id = ?", cv.Type).Get(&ir)
			if s.OpenIntegral == 1 && ir.Id != 0{

				fmt.Println("支付方式：", pv.Name)

				var cmp ConsumptionModePoint
				x.Where("store_id = ?", cv.StoreId).And("consumption_mode_id = ?", cv.Type).Get(&cmp)

				fmt.Println("cmp.Integral：", cmp.Integral)
				fmt.Println("cmp.AmountOfPoints：", cmp.AmountOfPoints)

				var thisPoint int64 = int64(pv.PaymentAmount)*cmp.Integral/cmp.AmountOfPoints

				mf := new(MemberInformation)
				x.Id(cv.MemberId).Get(mf)

				fmt.Println("mf.MemberPoints：", mf.MemberPoints)

				mf.MemberPoints += thisPoint
				x.Id(cv.MemberId).Update(mf)
				pv.ThisPoint = thisPoint
				x.Id(pv.Id).Update(pv)
				cv.ThisSumPoint += thisPoint
				x.Id(cv.Id).Update(cv)
			}

			if pv.PaymentTypeId == 308720610148614152{
				mf := new(MemberInformation)
				x.Id(cv.MemberId).Get(mf)
				mf.AccountAmount -= pv.PaymentAmount
				x.Id(cv.MemberId).Update(mf)
			}

			if pv.PaymentTypeId == 308720610148614151{
				mf := new(MemberInformation)
				x.Id(cv.MemberId).Get(mf)

				fmt.Println("mf.MemberPoints：", mf.MemberPoints)
				fmt.Println("s.PerIntegral：", s.PerIntegral)
				fmt.Println("s.Exchange：", s.Exchange)

				mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
				x.Id(mf.Id).Update(mf)
			}
		}

		for _, gv := range cv.GiftItemList {
			gv.Id = w.GetId()
			gv.ConsumptionId = cv.Id
			gv.CreatedAt = time.Now()
			gv.UpdatedAt = time.Now()
			x.Insert(gv)

			mpp.Id = w.GetId()
			mpp.ConsumptionId = cv.Id
			mpp.ItemId = gv.ItemId
			mpp.MemberInformationId = cv.MemberId
			mpp.Number = gv.Number
			mpp.Name = gv.Name
			mpp.Compose = gv.Compose
			mpp.TimesOfOriginalTreatment = gv.NumberOfGifts
			mpp.RemainingTimes = gv.NumberOfGifts
			mpp.OriginalPrice = gv.OriginalPrice
			mpp.CoursePrice = gv.TotalValue
			mpp.EffectiveDays = gv.EffectiveDays
			mpp.CreatedAt = time.Now()
			mpp.UpdatedAt = time.Now()
			x.Insert(&mpp)
		}
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (c *Consumption) PlaceAnOrderAsync(cv *Consumption) (map[string]interface{}, error){

	w := new(utils.Worker)
	var mpp MemberPurchasePackage

	if cv.Type == 308731091139690499 && cv.MemberType == 308720021171863552{

		var wg sync.WaitGroup
		wg.Add(5)

		cv.Id = w.GetId()
		cv.CreatedAt = time.Now()
		cv.UpdatedAt = time.Now()
		x.Insert(cv)

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			for _, cpv := range cv.ConsumptionProductList {

				cpv.Id = w.GetId()
				cpv.ConsumptionId = cv.Id
				cpv.CreatedAt = time.Now()
				cpv.UpdatedAt = time.Now()
				x.Insert(cpv)

				var p Products
				x.Id(cpv.ProductId).Get(&p)
				p.Stock -= 1
				x.Id(cpv.ProductId).Update(&p)

				for _, pcev := range cpv.ConsumptionEmployeeList {

					var pc Clerk
					x.Id(pcev.ClerkId).Get(&pc)
					pc.AchievementSum += pcev.Achievement
					x.Id(pcev.ClerkId).Update(&pc)

					pcev.Id = w.GetId()
					pcev.ConsumptionProductOrItemId = cpv.Id
					pcev.ConsumptionId = cv.Id
					pcev.CreatedAt = time.Now()
					pcev.UpdatedAt = time.Now()
					x.Insert(pcev)
				}

				for _, pcbv := range cpv.ConsumptionBeauticianList {

					var pc Clerk
					x.Id(pcbv.ClerkId).Get(&pc)
					pc.AchievementSum += pcbv.Achievement
					pc.ManualCostSum += pcbv.ManualCost
					x.Id(pcbv.ClerkId).Update(&pc)

					pcbv.Id = w.GetId()
					pcbv.ConsumptionProductOrItemId = cpv.Id
					pcbv.ConsumptionId = cv.Id
					pcbv.CreatedAt = time.Now()
					pcbv.UpdatedAt = time.Now()
					x.Insert(pcbv)
				}
			}

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			for _, civ := range cv.ConsumptionItemList {
				civ.Id = w.GetId()
				civ.ConsumptionId = cv.Id
				civ.CreatedAt = time.Now()
				civ.UpdatedAt = time.Now()
				x.Insert(civ)

				mpp.Id = w.GetId()
				mpp.ConsumptionId = cv.Id
				mpp.ItemId = civ.ItemId
				mpp.MemberInformationId = cv.MemberId
				mpp.Number = civ.Number
				mpp.Name = civ.Name
				mpp.Compose = civ.Compose
				mpp.TimesOfOriginalTreatment = civ.Frequency
				mpp.RemainingTimes = civ.Frequency
				mpp.OriginalPrice = civ.OriginalPrice
				mpp.CoursePrice = civ.Price
				mpp.EffectiveDays = civ.EffectiveDays
				mpp.CreatedAt = time.Now()
				mpp.UpdatedAt = time.Now()
				x.Insert(&mpp)

				for _, icev := range civ.ConsumptionEmployeeList {

					var ic Clerk
					x.Id(icev.ClerkId).Get(&ic)
					ic.AchievementSum += icev.Achievement
					x.Id(icev.ClerkId).Update(&ic)

					icev.Id = w.GetId()
					icev.ConsumptionProductOrItemId = civ.Id
					icev.ConsumptionId = cv.Id
					icev.CreatedAt = time.Now()
					icev.UpdatedAt = time.Now()
					x.Insert(icev)
				}

				for _, icbv := range civ.ConsumptionBeauticianList {

					var ic Clerk
					x.Id(icbv.ClerkId).Get(&ic)
					ic.AchievementSum += icbv.Achievement
					ic.ManualCostSum += icbv.ManualCost
					x.Id(icbv.ClerkId).Update(&ic)

					icbv.Id = w.GetId()
					icbv.ConsumptionProductOrItemId = civ.Id
					icbv.ConsumptionId = cv.Id
					icbv.CreatedAt = time.Now()
					icbv.UpdatedAt = time.Now()
					x.Insert(icbv)
				}
			}

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			for _, ctv := range cv.ConsumptionTreatmentList {

				ctv.Id = w.GetId()
				ctv.ConsumptionId = cv.Id
				ctv.CreatedAt = time.Now()
				ctv.UpdatedAt = time.Now()
				x.Insert(ctv)

				var tpList []*TreatmentProducts
				x.Where("treatment_id = ?", ctv.TreatmentId).Find(&tpList)
				for _, tp := range tpList {
					var p Products
					x.Id(tp.ProductId).Get(&p)
					p.Stock -= tp.Quantity
					x.Id(tp.ProductId).Update(&p)
				}

				var tiList []*TreatmentItems
				x.Where("treatment_id = ?", ctv.TreatmentId).Find(&tiList)
				for _, iv := range tiList {
					mpp.Id = w.GetId()
					mpp.ConsumptionId = cv.Id
					mpp.ItemId = iv.ItemId
					mpp.MemberInformationId = cv.MemberId
					mpp.Number = iv.Number
					mpp.Name = iv.Name
					mpp.Compose = iv.Compose
					mpp.TimesOfOriginalTreatment = iv.Frequency
					mpp.RemainingTimes = iv.Frequency
					mpp.OriginalPrice = iv.OriginalPrice
					mpp.CoursePrice = iv.Price
					mpp.EffectiveDays = iv.EffectiveDays
					mpp.CreatedAt = time.Now()
					mpp.UpdatedAt = time.Now()
					x.Insert(&mpp)
				}

				for _, tcev := range ctv.ConsumptionEmployeeList {

					var tc Clerk
					x.Id(tcev.ClerkId).Get(&tc)
					tc.AchievementSum += tcev.Achievement
					x.Id(tcev.ClerkId).Update(&tc)

					tcev.Id = w.GetId()
					tcev.ConsumptionProductOrItemId = ctv.Id
					tcev.ConsumptionId = cv.Id
					tcev.CreatedAt = time.Now()
					tcev.UpdatedAt = time.Now()
					x.Insert(tcev)
				}

				for _, tcbv := range ctv.ConsumptionBeauticianList {

					var tc Clerk
					x.Id(tcbv.ClerkId).Get(&tc)
					tc.AchievementSum += tcbv.Achievement
					tc.ManualCostSum += tcbv.ManualCost
					x.Id(tcbv.ClerkId).Update(&tc)

					tcbv.Id = w.GetId()
					tcbv.ConsumptionProductOrItemId = ctv.Id
					tcbv.ConsumptionId = cv.Id
					tcbv.CreatedAt = time.Now()
					tcbv.UpdatedAt = time.Now()
					x.Insert(tcbv)
				}
			}

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			var s Store
			x.Id(cv.StoreId).Get(&s)

			for _, pv := range cv.PaymentDetails {

				pv.Id = w.GetId()
				pv.ConsumptionId = cv.Id
				pv.CreatedAt = time.Now()
				pv.UpdatedAt = time.Now()
				x.Insert(pv)

				var ir IntegralRule
				x.Where("payment_method_id = ?", pv.PaymentTypeId).
					And("store_id = ?", cv.StoreId).
					And("consumption_mode_id = ?", cv.Type).Get(&ir)
				if s.OpenIntegral == 1 && ir.Id != 0 {

					fmt.Println("支付方式：", pv.Name)

					var cmp ConsumptionModePoint
					x.Where("store_id = ?", cv.StoreId).And("consumption_mode_id = ?", cv.Type).Get(&cmp)

					fmt.Println("cmp.Integral：", cmp.Integral)
					fmt.Println("cmp.AmountOfPoints：", cmp.AmountOfPoints)

					var thisPoint int64 = int64(pv.PaymentAmount) * cmp.Integral / cmp.AmountOfPoints

					mf := new(MemberInformation)
					x.Id(cv.MemberId).Get(mf)

					fmt.Println("mf.MemberPoints：", mf.MemberPoints)

					mf.MemberPoints += thisPoint
					x.Id(cv.MemberId).Update(mf)
					pv.ThisPoint = thisPoint
					x.Id(pv.Id).Update(pv)
					cv.ThisSumPoint += thisPoint
					x.Id(cv.Id).Update(cv)
				}

				if pv.PaymentTypeId == 308720610148614152 {
					mf := new(MemberInformation)
					x.Id(cv.MemberId).Get(mf)
					mf.AccountAmount -= pv.PaymentAmount
					x.Id(cv.MemberId).Update(mf)
				}

				if pv.PaymentTypeId == 308720610148614151 {
					mf := new(MemberInformation)
					x.Id(cv.MemberId).Get(mf)

					fmt.Println("mf.MemberPoints：", mf.MemberPoints)
					fmt.Println("s.PerIntegral：", s.PerIntegral)
					fmt.Println("s.Exchange：", s.Exchange)

					mf.MemberPoints -= int64(pv.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
					x.Id(mf.Id).Update(mf)
				}
			}

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			for _, gv := range cv.GiftItemList {
				gv.Id = w.GetId()
				gv.ConsumptionId = cv.Id
				gv.CreatedAt = time.Now()
				gv.UpdatedAt = time.Now()
				x.Insert(gv)

				mpp.Id = w.GetId()
				mpp.ConsumptionId = cv.Id
				mpp.ItemId = gv.ItemId
				mpp.MemberInformationId = cv.MemberId
				mpp.Number = gv.Number
				mpp.Name = gv.Name
				mpp.Compose = gv.Compose
				mpp.TimesOfOriginalTreatment = gv.NumberOfGifts
				mpp.RemainingTimes = gv.NumberOfGifts
				mpp.OriginalPrice = gv.OriginalPrice
				mpp.CoursePrice = gv.TotalValue
				mpp.EffectiveDays = gv.EffectiveDays
				mpp.CreatedAt = time.Now()
				mpp.UpdatedAt = time.Now()
				x.Insert(&mpp)
			}

			wg.Done()
		}()

		wg.Wait()
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func (ir *IntegralRule)QueryIntegralRule(sId int64) ([]*ConsumptionMode, error){
	var cms []*ConsumptionMode
	x.Find(&cms)
	for _, cmv := range cms{
		x.Find(&cmv.PaymentMethodList)

		x.Where("consumption_mode_id = ?", cmv.Id).And("store_id = ?", sId).Get(&cmv.ConsumptionModePoint)

		if cmv.Id == 308731091135496192{
			cmv.PaymentMethodList = cmv.PaymentMethodList[3:6]
		}else if cmv.Id == 308731091139690500 || cmv.Id == 308731091139690501{
			cmv.PaymentMethodList = nil
		}else {
			cmv.PaymentMethodList = cmv.PaymentMethodList[3:7]
		}
		for _, pmv := range cmv.PaymentMethodList{
			var irv IntegralRule
			x.Where("consumption_mode_id = ?", cmv.Id).And("store_id = ?", sId).And("payment_method_id = ?", pmv.Id).Get(&irv)
			if irv.Id != 0{
				pmv.Ident = true
			}
		}
	}
	return cms, nil
}

func (store *Store)InsertIntegralRule(cmList []*ConsumptionMode, sId int64)(map[string]interface{}, error){

	w := new(utils.Worker)

	for _, cm := range cmList{

		//cm.ConsumptionModePoint.StoreId = sId
		//cm.ConsumptionModePoint.ConsumptionModeId = cm.Id
		//x.Insert(cm.ConsumptionModePoint)

		x.Id(cm.ConsumptionModePoint.Id).Update(cm.ConsumptionModePoint)

		for _, pm := range cm.PaymentMethodList{
			var ir IntegralRule
			x.Where("consumption_mode_id = ?", cm.Id).And("store_id = ?", sId).And("payment_method_id = ?", pm.Id).Get(&ir)

			if pm.Ident{
				if ir.Id == 0{
					ir.Id = w.GetId()
					ir.StoreId = sId
					ir.ConsumptionModeId = cm.Id
					ir.PaymentMethodId = pm.Id
					ir.CreatedAt = time.Now()
					ir.UpdatedAt = time.Now()
					x.Insert(&ir)
				}
			}else {
				if ir.Id != 0{
					x.Id(ir.Id).Delete(&ir)
				}
			}
		}
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

type CancellationRecodes struct {
	Id int64 `xorm:"pk autoincr"`
	ConsumptionId int64
	State int
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (c *Consumption)Revoke(cId int64)(map[string]interface{}, error){

	w := new(utils.Worker)

	var cr = CancellationRecodes{
		Id:            w.GetId(),
		ConsumptionId: cId,
		State:         1,
		CreatedAt:     time.Now(),
		UpdatedAt:     time.Now(),
	}
	x.Insert(&cr)

	return map[string]interface{}{"message":"成功","code":200}, nil
	
	//var cv Consumption
	//x.Where("id = ?", cId).Get(&cv)
	//
	//x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionProductList)
	//for _, cp := range cv.ConsumptionProductList{
	//	x.Where("consumption_product_or_item_id = ?", cp.Id).Delete(cp.ConsumptionEmployeeList)
	//	for _, pcev := range cp.ConsumptionEmployeeList{
	//		var pc Clerk
	//		pc.AchievementSum -= pcev.Achievement
	//		x.Id(pcev.ClerkId).Update(&pc)
	//	}
	//
	//	x.Where("consumption_product_or_item_id = ?", cp.Id).Delete(cp.ConsumptionBeauticianList)
	//	for _, pcbv := range cp.ConsumptionBeauticianList{
	//		var pc Clerk
	//		pc.AchievementSum -= pcbv.Achievement
	//		pc.ManualCostSum -= pcbv.ManualCost
	//		x.Id(pcbv.ClerkId).Update(&pc)
	//	}
	//}
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionProducts))
	//
	//x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionItemList)
	//for _, ci := range cv.ConsumptionItemList{
	//	x.Where("consumption_product_or_item_id = ?", ci.Id).Delete(ci.ConsumptionEmployeeList)
	//	for _, icev := range ci.ConsumptionEmployeeList{
	//		var ic Clerk
	//		ic.AchievementSum -= icev.Achievement
	//		x.Id(icev.ClerkId).Update(&ic)
	//	}
	//
	//	x.Where("consumption_product_or_item_id = ?", ci.Id).Delete(ci.ConsumptionBeauticianList)
	//	for _, icbv := range ci.ConsumptionBeauticianList{
	//		var ic Clerk
	//		ic.AchievementSum -= icbv.Achievement
	//		ic.ManualCostSum -= icbv.ManualCost
	//		x.Id(icbv.ClerkId).Update(&ic)
	//	}
	//}
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionItems))
	//
	//x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionTreatmentList)
	//for _, ct := range cv.ConsumptionTreatmentList{
	//	x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(ct.ConsumptionEmployeeList)
	//	for _, icev := range ct.ConsumptionEmployeeList{
	//		var tc Clerk
	//		tc.AchievementSum -= icev.Achievement
	//		x.Id(icev.ClerkId).Update(&tc)
	//	}
	//	//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionEmployees))
	//
	//	x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(ct.ConsumptionBeauticianList)
	//	for _, tcbv := range ct.ConsumptionBeauticianList{
	//		var tc Clerk
	//		tc.AchievementSum -= tcbv.Achievement
	//		tc.ManualCostSum -= tcbv.ManualCost
	//		x.Id(tcbv.ClerkId).Update(&tc)
	//	}
	//	//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionBeautician))
	//}
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionTreatment))
	//
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionEmployees))
	//
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionBeautician))
	//
	//x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionPaymentMethods))
	//
	//mpp := new(MemberPurchasePackage)
	//x.Where("consumption_id = ?", cId).Delete(mpp)
	//
	//mi := new(MemberInformation)
	//mi.MemberPoints -= cv.ThisSumPoint
	//x.Id(cv.MemberId).Update(mi)
	//
	//cpm := new(ConsumptionPaymentMethods)
	//x.Where("consumption_id = ?", cId).And("payment_type_id = ?", 3).Get(cpm)
	//if cpm.Id != 0{
	//	mi.AccountAmount -= cpm.PaymentAmount
	//	x.Id(mi.Id).Update(mi)
	//}
	//
	//x.Where("consumption_id = ?", cId).Delete(cpm)
	//
	//cv.State = 2
	//x.Id(cId).Update(&cv)
	//
	//return map[string]interface{}{"message":"成功","code":200}, nil

}

func (c *Consumption)CancellationAudit(crId int64, pn int)(map[string]interface{}, error){

	var cr CancellationRecodes
	x.Id(crId).Get(&cr)

	var cv Consumption
	x.Where("id = ?", cr.ConsumptionId).Get(&cv)

	if pn == 1{

		x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionProductList)
		for _, cp := range cv.ConsumptionProductList{
			var p Products
			x.Id(cp.ProductId).Get(&p)
			p.Stock += 1
			x.Id(cp.ProductId).Update(&p)

			x.Where("consumption_product_or_item_id = ?", cp.Id).Find(&cp.ConsumptionEmployeeList)
			for _, pcev := range cp.ConsumptionEmployeeList{
				var pc Clerk
				x.Id(pcev.ClerkId).Get(&pc)
				pc.AchievementSum -= pcev.Achievement
				x.Id(pcev.ClerkId).Update(&pc)
			}

			x.Where("consumption_product_or_item_id = ?", cp.Id).Find(&cp.ConsumptionBeauticianList)
			for _, pcbv := range cp.ConsumptionBeauticianList{
				var pc Clerk
				x.Id(pcbv.ClerkId).Get(&pc)
				pc.AchievementSum -= pcbv.Achievement
				pc.ManualCostSum -= pcbv.ManualCost
				x.Id(pcbv.ClerkId).Update(&pc)
			}
		}
		x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionProducts))

		x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionItemList)
		for _, ci := range cv.ConsumptionItemList{
			x.Where("consumption_product_or_item_id = ?", ci.Id).Find(&ci.ConsumptionEmployeeList)
			for _, icev := range ci.ConsumptionEmployeeList{
				var ic Clerk
				x.Id(icev.ClerkId).Get(&ic)
				ic.AchievementSum -= icev.Achievement
				x.Id(icev.ClerkId).Update(&ic)
			}

			x.Where("consumption_product_or_item_id = ?", ci.Id).Find(&ci.ConsumptionBeauticianList)
			for _, icbv := range ci.ConsumptionBeauticianList{
				var ic Clerk
				x.Id(icbv.ClerkId).Get(&ic)
				ic.AchievementSum -= icbv.Achievement
				ic.ManualCostSum -= icbv.ManualCost
				x.Id(icbv.ClerkId).Update(&ic)
			}
		}
		x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionItems))

		x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionTreatmentList)
		fmt.Println("cv.ConsumptionTreatmentList：", cv.ConsumptionTreatmentList)

		for _, ct := range cv.ConsumptionTreatmentList{
			var tpList []*TreatmentProducts
			x.Where("treatment_id = ?", ct.TreatmentId).Find(&tpList)
			for _, tp := range tpList {
				var p Products
				x.Id(tp.ProductId).Get(&p)
				p.Stock += tp.Quantity
				x.Id(tp.ProductId).Update(&p)
			}

			x.Where("consumption_product_or_item_id = ?", ct.Id).Find(&ct.ConsumptionEmployeeList)
			fmt.Println("ct.ConsumptionEmployeeList：", ct.ConsumptionEmployeeList)

			for _, tcev := range ct.ConsumptionEmployeeList{
				var tc Clerk
				x.Id(tcev.ClerkId).Get(&tc)

				fmt.Println("tc.AchievementSum：", tc.AchievementSum)
				fmt.Println("tcev.Achievement：", tcev.Achievement)

				tc.AchievementSum -= tcev.Achievement

				fmt.Println("tc.AchievementSum：", tc.AchievementSum)

				x.Id(tcev.ClerkId).Cols("achievement_sum").Update(&tc)
			}
			//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionEmployees))

			x.Where("consumption_product_or_item_id = ?", ct.Id).Find(&ct.ConsumptionBeauticianList)
			fmt.Println("ct.ConsumptionBeauticianList：", ct.ConsumptionBeauticianList)

			for _, tcbv := range ct.ConsumptionBeauticianList{
				var tc Clerk
				x.Id(tcbv.ClerkId).Get(&tc)
				tc.AchievementSum -= tcbv.Achievement
				tc.ManualCostSum -= tcbv.ManualCost
				x.Id(tcbv.ClerkId).Cols("achievement_sum", "manual_cost_sum").Update(&tc)
			}
			//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionBeautician))
		}
		x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionTreatment))

		x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionEmployees))

		x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionBeautician))

		mpp := new(MemberPurchasePackage)
		x.Where("consumption_id = ?", cr.ConsumptionId).Delete(mpp)

		mi := new(MemberInformation)
		x.Id(cv.MemberId).Get(mi)
		mi.MemberPoints -= cv.ThisSumPoint
		x.Id(cv.MemberId).Update(mi)

		cpm := new(ConsumptionPaymentMethods)
		x.Where("consumption_id = ?", cr.ConsumptionId).And("payment_type_id = ?", 308720610148614152).Get(cpm)
		if cpm.Id != 0{
			mi.AccountAmount += cpm.PaymentAmount
			x.Id(mi.Id).Update(mi)
		}

		var s Store
		x.Id(cv.StoreId).Get(&s)
		cpm1 := new(ConsumptionPaymentMethods)
		x.Where("consumption_id = ?", cr.ConsumptionId).And("payment_type_id = ?", 308720610148614151).Get(cpm1)
		if cpm1.Id != 0{
			mi1 := new(MemberInformation)
			x.Id(cv.MemberId).Get(mi1)
			mi1.MemberPoints += int64(cpm1.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
			x.Id(cv.MemberId).Update(mi1)
		}

		x.Where("consumption_id = ?", cr.ConsumptionId).Delete(new(ConsumptionPaymentMethods))

		g := new(GiftItems)
		x.Where("consumption_id = ?", cr.ConsumptionId).Delete(g)

		cv.State = 2
		x.Id(cr.ConsumptionId).Update(&cv)

		cr.State = 2
		x.Id(cr.Id).Update(&cr)

		return map[string]interface{}{"message":"成功","code":200}, nil
	}else {

		cv.State = 3
		x.Id(cv.Id).Update(&cv)

		cr.State = 3
		x.Id(cr.Id).Update(&cr)

		return map[string]interface{}{"message": "成功", "code": 200}, nil
	}
}

func (c *Consumption)CancellationAuditAsync(crId int64, pn int)(map[string]interface{}, error){

	var cr CancellationRecodes
	x.Id(crId).Get(&cr)

	var cv Consumption
	x.Where("id = ?", cr.ConsumptionId).Get(&cv)

	if pn == 1{

		var wg sync.WaitGroup
		wg.Add(4)

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionProductList)
			for _, cp := range cv.ConsumptionProductList {
				var p Products
				x.Id(cp.ProductId).Get(&p)
				p.Stock += 1
				x.Id(cp.ProductId).Update(&p)

				x.Where("consumption_product_or_item_id = ?", cp.Id).Find(&cp.ConsumptionEmployeeList)
				for _, pcev := range cp.ConsumptionEmployeeList {
					var pc Clerk
					x.Id(pcev.ClerkId).Get(&pc)
					pc.AchievementSum -= pcev.Achievement
					x.Id(pcev.ClerkId).Update(&pc)
				}

				x.Where("consumption_product_or_item_id = ?", cp.Id).Find(&cp.ConsumptionBeauticianList)
				for _, pcbv := range cp.ConsumptionBeauticianList {
					var pc Clerk
					x.Id(pcbv.ClerkId).Get(&pc)
					pc.AchievementSum -= pcbv.Achievement
					pc.ManualCostSum -= pcbv.ManualCost
					x.Id(pcbv.ClerkId).Update(&pc)
				}
			}
			x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionProducts))

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionItemList)
			for _, ci := range cv.ConsumptionItemList {
				x.Where("consumption_product_or_item_id = ?", ci.Id).Find(&ci.ConsumptionEmployeeList)
				for _, icev := range ci.ConsumptionEmployeeList {
					var ic Clerk
					x.Id(icev.ClerkId).Get(&ic)
					ic.AchievementSum -= icev.Achievement
					x.Id(icev.ClerkId).Update(&ic)
				}

				x.Where("consumption_product_or_item_id = ?", ci.Id).Find(&ci.ConsumptionBeauticianList)
				for _, icbv := range ci.ConsumptionBeauticianList {
					var ic Clerk
					x.Id(icbv.ClerkId).Get(&ic)
					ic.AchievementSum -= icbv.Achievement
					ic.ManualCostSum -= icbv.ManualCost
					x.Id(icbv.ClerkId).Update(&ic)
				}
			}
			x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionItems))

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			x.Where("consumption_id = ?", cv.Id).Find(&cv.ConsumptionTreatmentList)
			fmt.Println("cv.ConsumptionTreatmentList：", cv.ConsumptionTreatmentList)

			for _, ct := range cv.ConsumptionTreatmentList {
				var tpList []*TreatmentProducts
				x.Where("treatment_id = ?", ct.TreatmentId).Find(&tpList)
				for _, tp := range tpList {
					var p Products
					x.Id(tp.ProductId).Get(&p)
					p.Stock += tp.Quantity
					x.Id(tp.ProductId).Update(&p)
				}

				x.Where("consumption_product_or_item_id = ?", ct.Id).Find(&ct.ConsumptionEmployeeList)
				fmt.Println("ct.ConsumptionEmployeeList：", ct.ConsumptionEmployeeList)

				for _, tcev := range ct.ConsumptionEmployeeList {
					var tc Clerk
					x.Id(tcev.ClerkId).Get(&tc)

					fmt.Println("tc.AchievementSum：", tc.AchievementSum)
					fmt.Println("tcev.Achievement：", tcev.Achievement)

					tc.AchievementSum -= tcev.Achievement

					fmt.Println("tc.AchievementSum：", tc.AchievementSum)

					x.Id(tcev.ClerkId).Cols("achievement_sum").Update(&tc)
				}
				//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionEmployees))

				x.Where("consumption_product_or_item_id = ?", ct.Id).Find(&ct.ConsumptionBeauticianList)
				fmt.Println("ct.ConsumptionBeauticianList：", ct.ConsumptionBeauticianList)

				for _, tcbv := range ct.ConsumptionBeauticianList {
					var tc Clerk
					x.Id(tcbv.ClerkId).Get(&tc)
					tc.AchievementSum -= tcbv.Achievement
					tc.ManualCostSum -= tcbv.ManualCost
					x.Id(tcbv.ClerkId).Cols("achievement_sum", "manual_cost_sum").Update(&tc)
				}
				//x.Where("consumption_product_or_item_id = ?", ct.Id).Delete(new(ConsumptionBeautician))
			}

			wg.Done()
		}()

		go func() {
			defer func() {
				// 捕获异常 防止waitGroup阻塞
				if err := recover(); err != nil {
					wg.Done()
				}
			}()

			x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionTreatment))

			x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionEmployees))

			x.Where("consumption_id = ?", cv.Id).Delete(new(ConsumptionBeautician))

			mpp := new(MemberPurchasePackage)
			x.Where("consumption_id = ?", cr.ConsumptionId).Delete(mpp)

			mi := new(MemberInformation)
			x.Id(cv.MemberId).Get(mi)
			mi.MemberPoints -= cv.ThisSumPoint
			x.Id(cv.MemberId).Update(mi)

			cpm := new(ConsumptionPaymentMethods)
			x.Where("consumption_id = ?", cr.ConsumptionId).And("payment_type_id = ?", 308720610148614152).Get(cpm)
			if cpm.Id != 0 {
				mi.AccountAmount += cpm.PaymentAmount
				x.Id(mi.Id).Update(mi)
			}

			var s Store
			x.Id(cv.StoreId).Get(&s)
			cpm1 := new(ConsumptionPaymentMethods)
			x.Where("consumption_id = ?", cr.ConsumptionId).And("payment_type_id = ?", 308720610148614151).Get(cpm1)
			if cpm1.Id != 0 {
				mi1 := new(MemberInformation)
				x.Id(cv.MemberId).Get(mi1)
				mi1.MemberPoints += int64(cpm1.PaymentAmount) / int64(s.PerIntegral/s.Exchange)
				x.Id(cv.MemberId).Update(mi1)
			}

			x.Where("consumption_id = ?", cr.ConsumptionId).Delete(new(ConsumptionPaymentMethods))

			g := new(GiftItems)
			x.Where("consumption_id = ?", cr.ConsumptionId).Delete(g)

			cv.State = 2
			x.Id(cr.ConsumptionId).Update(&cv)

			cr.State = 2
			x.Id(cr.Id).Update(&cr)

			wg.Done()
		}()

		wg.Wait()

		return map[string]interface{}{"message":"成功","code":200}, nil
	}else {

		cv.State = 3
		x.Id(cv.Id).Update(&cv)

		cr.State = 3
		x.Id(cr.Id).Update(&cr)

		return map[string]interface{}{"message": "成功", "code": 200}, nil
	}
}

type CashSetting struct {
	ConsumptionModeList []*ConsumptionMode
	ModifiableItemList []*ModifiableItem
	PaymentMethodLsit []*PaymentMethods
}

func (c *Consumption)QueryCashSetting(ctId int64, sId int64)(*CashSetting, error){
	var cs CashSetting

	x.Join("INNER", "customer_type_consumption_mode", "customer_type_consumption_mode.consumption_mode_id = consumption_mode.id").
		Where("customer_type_consumption_mode.customer_type_id = ?", ctId).And("customer_type_consumption_mode.store_id = ?", sId).
		Find(&cs.ConsumptionModeList)

	x.Join("INNER", "cashier_rule", "cashier_rule.modifiable_item_id = modifiable_item.id").
		Where("cashier_rule.customer_type_id = ?", ctId).And("cashier_rule.store_id = ?", sId).
		Find(&cs.ModifiableItemList)

	x.Join("INNER", "customer_type_payment_method", "customer_type_payment_method.payment_method_id = payment_methods.id").
		Where("customer_type_payment_method.customer_type_id = ?", ctId).And("customer_type_payment_method.store_id = ?", sId).
		Find(&cs.PaymentMethodLsit)

	return &cs, nil
}

func (store *Store)QueryCashierRule(sId int64)([]*CustomerType, error){

	var ctList []*CustomerType
	x.Find(&ctList)

	for _, ct := range ctList{
		x.Find(&ct.ModifiableItemList)
		for _, mi := range ct.ModifiableItemList {
			var cr CashierRule
			x.Where("store_id = ?", sId).And("customer_type_id = ?", ct.Id).And("modifiable_item_id = ?", mi.Id).Get(&cr)
			if cr.Id != 0{
				mi.Modifi = true
			}
		}
	}

	return ctList, nil
}

func (store *Store)QueryPaymentMethod(sId int64)([]*CustomerType, error){

	var ctList []*CustomerType
	x.Find(&ctList)

	for _, ct := range ctList{
		x.Find(&ct.PaymentMethodLsit)
		if ct.Id == 308720021171863553{
			ct.PaymentMethodLsit = ct.PaymentMethodLsit[1:6]
		}
		for _, pm := range ct.PaymentMethodLsit {
			var ctpm CustomerTypePaymentMethod
			x.Where("store_id = ?", sId).And("customer_type_id = ?", ct.Id).And("payment_method_id = ?", pm.Id).Get(&ctpm)
			if ctpm.Id != 0{
				pm.Ident = true
			}
		}
	}

	return ctList, nil

}

type RefundRecords struct {
	Id int64 `xorm:"pk autoincr"`
	MemberInformationId int64
	MemberPurchasePackageListStr string
	ReturnCard bool
	State int
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (m *MemberInformation)CourseRefund(mId int64, i interface{}, rc int)(map[string]interface{}, error){

	w := new(utils.Worker)

	var rr = RefundRecords{
		Id                 : w.GetId(),
		MemberInformationId: mId,
		MemberPurchasePackageListStr: i.(string),
		State:               1,
		CreatedAt:           time.Now(),
		UpdatedAt:           time.Now(),
	}

	if rc == 1{
		rr.ReturnCard = true
	}

	x.Insert(&rr)

	return map[string]interface{}{"message": "成功", "code": 200}, nil

	//var mppLsit []*MemberPurchasePackage
	//x.Where("member_information_id = ?", mId).Find(&mppLsit)
	//
	//var sum float64
	//if i == nil{
	//	for _, mpp := range mppLsit {
	//
	//		ref := mpp.OriginalPrice / float64(mpp.TimesOfOriginalTreatment) * float64(mpp.TimesOfOriginalTreatment-mpp.RemainingTimes)
	//		if ref > 0 {
	//			sum += ref
	//		} else {
	//			sum += 0
	//		}
	//	}
	//
	//	var mi MemberInformation
	//	mi.AccountAmount += sum
	//
	//	var mpp MemberPurchasePackage
	//	x.Where("member_information_id = ?", mId).Delete(&mpp)
	//
	//	return map[string]interface{}{"message": "成功", "code": 200, "date": mi.AccountAmount}, nil
	//}else {
	//
	//	mppIdStr := i.(string)
	//	mppIdStrList := strings.Split(mppIdStr, ",")
	//
	//	for _, mis := range mppIdStrList {
	//		mv, err := strconv.ParseInt(mis, 10, 64)
	//		if err != nil {
	//			return map[string]interface{}{"message": "失败", "code": 400,"date":nil}, nil
	//		}
	//		for _, mpp := range mppLsit {
	//			if mv == mpp.Id {
	//				ref := mpp.OriginalPrice / float64(mpp.TimesOfOriginalTreatment) * float64(mpp.TimesOfOriginalTreatment-mpp.RemainingTimes)
	//				if ref > 0 {
	//					sum += ref
	//				} else {
	//					sum += 0
	//				}
	//
	//				x.Id(mpp.Id).Delete(mpp)
	//			}
	//		}
	//	}
	//
	//	var mi MemberInformation
	//	mi.AccountAmount += sum
	//	x.Id(mId).Update(&mi)
	//
	//	return map[string]interface{}{"message": "成功", "code": 200, "date": mi.AccountAmount}, nil
	//}
}

func (m *MemberInformation)ReviewRefund(rrId int64, adopt int)(map[string]interface{}, error){

	var rr RefundRecords
	x.Id(rrId).Get(&rr)

	if adopt == 1 {

		var mppLsit []*MemberPurchasePackage
		x.Where("member_information_id = ?", rr.MemberInformationId).Find(&mppLsit)

		var sum float64

		mppIdStrList := strings.Split(rr.MemberPurchasePackageListStr, ",")

		for _, mis := range mppIdStrList {
			mv, err := strconv.ParseInt(mis, 10, 64)
			if err != nil {
				return map[string]interface{}{"message": "失败", "code": 400, "date": nil}, nil
			}
			for _, mpp := range mppLsit {
				if mv == mpp.Id {
					ref := mpp.CoursePrice - mpp.OriginalPrice / float64(mpp.TimesOfOriginalTreatment) * float64(mpp.UsageTimes)
					if ref > 0 {
						sum += ref
					} else {
						sum += 0
					}

					x.Id(mpp.Id).Delete(mpp)
				}
			}
		}

		var mi MemberInformation
		x.Id(rr.MemberInformationId).Get(&mi)
		if rr.ReturnCard == true{
			mi.AccountAmount += sum
			x.Id(rr.MemberInformationId).Update(&mi)
		}

		rr.State = 2
		x.Id(rr.Id).Update(&rr)

		return map[string]interface{}{"message": "成功", "code": 200, "data": mi.AccountAmount}, nil
	}else {

		rr.State = 3
		x.Id(rr.Id).Update(&rr)

		return map[string]interface{}{"message": "成功", "code": 200}, nil
	}
}

func (m *MemberInformation)CancelCard(mId int64)(map[string]interface{}, error){

	hm, err := m.CourseRefund(mId, nil, 2)
	if err != nil {
		return map[string]interface{}{"message": "失败", "code": 400}, nil
	}

	x.Where("member_information_id = ?", mId).Delete(new(MemberPurchasePackage))

	x.Id(mId).Delete(new(MemberInformation))

	return map[string]interface{}{"message":"成功","code":200, "date":hm["date"]}, nil
}

type Region struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	RoomList []*Room
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Room struct {
	Id int64 `xorm:"pk autoincr"`
	RegionId int64
	BedTotal int
	BedRemaining int
	Full bool
	BedList []*Bed `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Bed struct {
	Id int64 `xorm:"pk autoincr"`
	RoomId int64
	Number int
	Occupier int64
	OccupierName string
	Enable bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

func CreateRoom(r *Room)(map[string]interface{}, error){

	x.Insert(r)
	for i:= 1; i<= r.BedTotal; i++ {
		var b = Bed{
			RoomId:    r.Id,
			Number:    i,
			Enable:    false,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(b)
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func Occupy(mmId int64, bId int64, rId int64)(map[string]interface{}, error){

	var mm MeiyeMember
	x.Id(mmId).Get(&mm)

	var b Bed
	b.Occupier = mm.Id
	b.OccupierName = mm.Name
	b.Enable = true
	x.Id(bId).Update(&b)

	var r Room
	x.Id(rId).Get(&r)
	r.BedRemaining -= 1
	if r.BedRemaining == 0{
		r.Full = true
	}
	x.Id(rId).Update(&r)


	return map[string]interface{}{"message":"成功","code":200}, nil
}

func QueryRoom()(){

	var rgList []*Region
	x.Find(&rgList)

	for _, rg := range rgList{
		x.Where("region_id = ?", rg.Id).Find(&rg.RoomList)

		for _, r := range rg.RoomList{
			x.Where("room_id = ?", r.Id).Find(&r.BedList)
		}
	}
}

type ProjectPerformance struct {
	ConsumptionDate string
	ItemName string
	SumAchievement float64
}

type PackagePerformance struct {
	CreatedAt time.Time
	ItemName string
	SumAchievement float64
}

func TrendAnalysis(st string, et string, d string)(){

	s := x.NewSession()

	if st != ""{
		s = s.And("created_at >= ?", st)
	}

	if et != ""{
		s = s.And("created_at <= ?", et)
	}

	if d != ""{
		s = s.And("consumption_date = ?", d)
	}

	var prpList []*ProjectPerformance
	s.Table("consumption_items").
		Select("consumption_date, name, sum(achievement)").
		GroupBy("consumption_date").
		Find(&prpList)

	var papList []*PackagePerformance
	s.Table("consumption_treatment").
		Select("consumption_date, name, sum(achievement)").
		GroupBy("consumption_date").
		Find(&papList)

}

func SalesStatistics(sId int64, r int64, st string, et string, d string)([]*Items, error){

	var iList []*Items
	x.Where("store_id = ?", sId).Find(&iList)

	s := x.NewSession()

	if sId != 0{
		s = s.And("consumption.store_id = ?", sId)
	}

	if r != 0{
		s = s.Join("INNER", "store", "store.id = consumption.store_id").And("store.region = ?", r)
	}

	if st != ""{
		s = s.And("created_at >= ?", st)
	}

	if et != ""{
		s = s.And("created_at <= ?", et)
	}

	if d != ""{
		s = s.And("consumption_date = ?", d)
	}

	for _, i := range iList{
		storeSale , sErr := s.Join("INNER", "consumption", "consumption.id = consumption_items.consumption_id").
			Where("consumption_items.item_id = ?", i.Id).
			And("consumption.source = ?", 1).
			Count(new(ConsumptionItems))
		if sErr != nil{
			return nil, sErr
		}
		i.StoreSale = storeSale

		storePackage, pErr := s.Join("INNER", "consumption", "consumption.id = consumption_treatment.consumption_id").
			Join("INNER","treatment_items", "consumption_treatment.treatment_id = treatment_items.treatment_id").
			Where("treatment_items.item_id = ?", i.Id).
			And("consumption.source = ?", 1).
			SumInt(new(TreatmentItems), "treatment_items.frequency")
		if pErr != nil{
			return nil, pErr
		}
		i.StorePackage = storePackage

		cashPerformance, cErr := s.Join("INNER", "consumption", "consumption.id = consumption_items.consumption_id").
			Where("consumption_items.item_id = ?", i.Id).
			SumInt(new(ConsumptionItems), "achievement")
		if cErr != nil{
			return nil, cErr
		}
		i.CashPerformance = cashPerformance

		consumptionPerformance, cpErr := s.Join("INNER", "consumption","consumption_member_purchase_package.consumption_id = consumption.id").
			Where("consumption_member_purchase_package.item_id = ?", i.Id).
			SumInt(new(ConsumptionMemberPurchasePackage), "achievement")
		if cpErr != nil{
			return nil, cpErr
		}
		i.ConsumptionPerformance = consumptionPerformance
	}

	return iList, nil
}
